package cc.vv.baselibrary.activity.components.watcherImage;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.activity.BaseActivity;
import cc.vv.baselibrary.bean.PublicViewHolder;
import cc.vv.baselibrary.util.CommonUtil;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.LKPermissionUtil;
import cc.vv.baselibrary.util.LKToastUtil;
import cc.vv.baselibrary.vFinal.BTKey;
import cc.vv.baselibrary.vFinal.BTParamKey;
import cc.vv.baselibrary.view.BtViewPager;
import cc.vv.baselibrary.view.DialogListView;
import cc.vv.baselibrary.view.jzvd.JZMediaManager;
import cc.vv.baselibrary.view.jzvd.JZVideoPlayer;
import cc.vv.baselibrary.view.jzvd.JZVideoPlayerStandard;
import cc.vv.baselibrary.view.photoView.PhotoView;
import cc.vv.lkbasecomponent.util.LKBarUtil;
import cc.vv.lkimagecomponent2.LKImage;
import cc.vv.lkimagecomponent2.downloadplugin.DownLoadCallback;
import cc.vv.lkimagecomponent2.loaderplugin.TargetViewCallback;
import cc.vv.lklibrary.log.LogOperate;

/**
 * 大图查看界面
 *
 * @author dup
 */

public class ImageWatcherActivity extends BaseActivity {

    /**
     * 文件保存路径
     */
    private String path = Environment.getExternalStorageDirectory()
            + File.separator + Environment.DIRECTORY_DCIM
            + File.separator + "BTong";

    private ViewHolder mViewHolder;
    private List<String> mListUrl = new ArrayList<>();
    private int mCurrentPosition = 0;

    private ViewPagerAdapter viewPagerAdapter;
    private ObjectAnimator alpha;
    private String mPrivateChatTag;

    @Override
    protected int initLayoutRes() {
        return R.layout.activity_image_watcher;
    }

    @Override
    protected PublicViewHolder initViewHolderObject() {
        mViewHolder = new ViewHolder();
        return mViewHolder;
    }

    private class ViewHolder extends PublicViewHolder {
        private RelativeLayout rl_aiw_layout;
        private BtViewPager vp_aiw_photo;
        private TextView tv_aiw_image_count;
    }

    @Override
    protected void baseOnClick(int viewId) {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setStatusBarVisible(false);
    }

    @Override
    protected void initView(Bundle bundle) {
        super.initView(bundle);
        LKBarUtil.setTransparent(this);
        try {
            try {
                mPrivateChatTag = getIntent().getExtras().getString(BTParamKey.SECRET_CHAT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mListUrl = getIntent().getExtras().getStringArrayList(BTParamKey.INTENT_IMGS_URLS);
            if (mListUrl == null || mListUrl.isEmpty()) {
                String url = getIntent().getStringExtra(BTParamKey.INTENT_IMGS_URLS);
                if (!TextUtils.isEmpty(url)) {
                    mListUrl = new ArrayList<>(1);
                    mListUrl.add(url);
                }
            }
        } catch (Exception e) {
            LogOperate.e(e.getMessage(), e);
        }
        if (mListUrl == null) {
            mListUrl = new ArrayList<>();
        }

        try {
            mCurrentPosition = getIntent().getExtras().getInt(BTParamKey.INTENT_IMGS_POSITION);
            if (mCurrentPosition >= mListUrl.size()) {
                LogOperate.e("大图查看,position越界!默认置为0");
                mCurrentPosition = 0;
            }
        } catch (Exception e) {
            LogOperate.e(e.getMessage(), e);
            mCurrentPosition = 0;
        }
        viewPagerAdapter = new ViewPagerAdapter(mListUrl);
        mViewHolder.vp_aiw_photo.setAdapter(viewPagerAdapter);
        mViewHolder.vp_aiw_photo.setCurrentItem(mCurrentPosition);
        if (mListUrl == null || mListUrl.size() <= 1) {
            mViewHolder.tv_aiw_image_count.setText("");
        } else {
            mViewHolder.tv_aiw_image_count.setText(mCurrentPosition + 1 + "/" + mListUrl.size());
        }
        mViewHolder.vp_aiw_photo.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mCurrentPosition = position;
                mViewHolder.tv_aiw_image_count.setText(mCurrentPosition + 1 + "/" + mListUrl.size());
            }
        });


        mViewHolder.vp_aiw_photo.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {
                    if (JZMediaManager.isPlaying()) {
                        JZVideoPlayer.goOnPlayOnPause();
                    }
                } catch (Exception e) {
                    LKLogUtil.e(e.getMessage(), e);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

//        startAnimation();不要启动动画了
    }


    private void endAnimation() {
        setStatusBarVisible(true);
        alpha = ObjectAnimator.ofFloat(mViewHolder.rl_aiw_layout, "alpha", 1, 0);
        alpha.setDuration(400);
        alpha.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ImageWatcherActivity.this.finish();
            }
        });
        alpha.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (alpha != null) {
            alpha.cancel();
        }
        JZVideoPlayer.releaseAllVideos();
    }

    /**
     * 显示和隐藏状态栏
     *
     * @param show
     */
    private void setStatusBarVisible(boolean show) {
        if (show) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    /**
     * 保存图片
     */
    private void saveImage(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        boolean sdPermission = LKPermissionUtil.getInstance().requestSD(this);
        if (sdPermission) {
            File file = new File(path, System.currentTimeMillis() + "BTong.jpg");
            LKImage.downLoad().downLoad(url, file.getAbsolutePath(), new DownLoadCallback() {
                @Override
                public void onStart(String filePath) {
                    super.onStart(filePath);
//                    LKToastUtil.showToastShort("开始保存");
                }

                @Override
                public void onSuccess(String filepath) {
                    // 其次把文件插入到系统图库
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.DATA, filepath);
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    Uri uri = ImageWatcherActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    // 最后通知图库更新
                    ImageWatcherActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.parse("file://" + filepath)));
                    LKToastUtil.showToastShort("成功保存到相册");
                }

                @Override
                public void onFail(String filePath) {
                    super.onFail(filePath);
                    LKToastUtil.showToastShort("保存失败");
                }
            });
        }
    }


    /**
     * 图片展示adapter
     */
    private class ViewPagerAdapter extends PagerAdapter {
        private List<String> mList;

        public ViewPagerAdapter(List<String> mList) {
            this.mList = mList;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            String imgPath = mList.get(position);
            if (CommonUtil.isVideoFile(imgPath)) {
                JZVideoPlayerStandard videoView = (JZVideoPlayerStandard) LayoutInflater.from(container.getContext())
                        .inflate(R.layout.activity_normal_video_player, container, false);
                videoView.setUp(imgPath, JZVideoPlayer.SCREEN_WINDOW_NORMAL, TextUtils.isEmpty(" ") ? " " + "" : " ");
                container.addView(videoView);
                return videoView;
            } else {
                View inflate = LayoutInflater.from(ImageWatcherActivity.this).inflate(R.layout.adapter_photo_shower, null);
                final PhotoView img = inflate.findViewById(R.id.iv_show);
                ImageView imgGif = inflate.findViewById(R.id.iv_show_gif);
                img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        endAnimation();
                    }
                });
                imgGif.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        endAnimation();
                    }
                });
                if (!TextUtils.equals(BTParamKey.SECRET_CHAT, mPrivateChatTag)) {
                    img.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            final List<DialogListView.DialogListObj> list = new ArrayList<>();
                            list.add(new DialogListView.DialogListObj(BTKey.BTKEY_INT_0, "保存"));
                            list.add(new DialogListView.DialogListObj(BTKey.BTKEY_INT_1, "取消"));
                            DialogListView.getInstance().initDialog(ImageWatcherActivity.this, list, new DialogListView.OperateInter() {
                                @Override
                                public void onItemClick(DialogListView.DialogListObj dialogListObj) {
                                    if (dialogListObj.type == BTKey.BTKEY_INT_0) {
                                        //保存点击
                                        try {
                                            saveImage(mListUrl.get(mCurrentPosition));
                                        } catch (IndexOutOfBoundsException e) {
                                            LogOperate.e("图片下载,数组越界", e);
                                        }
                                    }
                                }
                            });
                            return true;
                        }
                    });
                    imgGif.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            final List<DialogListView.DialogListObj> list = new ArrayList<>();
                            list.add(new DialogListView.DialogListObj(BTKey.BTKEY_INT_0, "保存"));
                            list.add(new DialogListView.DialogListObj(BTKey.BTKEY_INT_1, "取消"));
                            DialogListView.getInstance().initDialog(ImageWatcherActivity.this, list, new DialogListView.OperateInter() {
                                @Override
                                public void onItemClick(DialogListView.DialogListObj dialogListObj) {
                                    if (dialogListObj.type == BTKey.BTKEY_INT_0) {
                                        //保存点击
                                        try {
                                            saveImage(mListUrl.get(mCurrentPosition));
                                        } catch (IndexOutOfBoundsException e) {
                                            LogOperate.e("图片下载,数组越界", e);
                                        }
                                    }
                                }
                            });
                            return true;
                        }
                    });
                }
                imgGif.setVisibility(View.GONE);
                img.setVisibility(View.VISIBLE);

                LKImage.load().load(imgPath).placeHolder(R.mipmap.icon_default_16_9).crossFade()
                        .error(R.mipmap.icon_def_image).
                        thumbnail(0.2f).into(new TargetViewCallback<PhotoView>(img) {
                    @Override
                    public void onSuccess(Drawable drawable) {
                        target.setImageDrawable(drawable);
                    }

                    @Override
                    public void onStart(Drawable placeholder) {
                        super.onStart(placeholder);
                        target.setImageDrawable(placeholder);
                    }

                    @Override
                    public void onFail(Drawable errorDrawable) {
                        super.onFail(errorDrawable);
                        target.setImageDrawable(errorDrawable);
                    }
                });

                container.addView(inflate);
                return inflate;
            }
        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((View) view);
        }

        @Override
        public int getCount() {
            return mList.size();
        }


        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }

}
